<template>
  <view class="mine-page">
    <!-- 1. 顶部用户信息区（强化视觉层次） -->
    <view class="user-info-container">
      <view class="user-info">
        <view class="avatar-wrap">
          <!-- 补充图片加载失败容错 -->
          <image 
            class="avatar" 
            :src="userInfo.avatar || defaultAvatar" 
            mode="aspectFill"
            @error="handleImgError"
          ></image>
        </view>
        <view class="user-detail">
          <text class="nickname">{{ isLogin ? (userInfo.username || userInfo.phone || '已登录') : '未登录' }}</text>
          <text class="user-id">{{ isLogin ? `用户ID: ${userInfo.id}` : '' }}</text>
          <text class="desc">{{ isLogin ? (userInfo.phone ? `手机号：${userInfo.phone}` : '管理我的书架与个人信息') : '登录后可使用全部功能' }}</text>
        </view>
        <!-- 未登录时增加"去登录"快捷按钮 -->
        <navigator 
          class="login-btn--small" 
          url="/pages/login/login"
          open-type="navigate"
          v-if="!isLogin"
        >
          去登录
        </navigator>
      </view>
    </view>

    <!-- 2. 功能区（优化排列与交互） -->
    <view class="menu-list">
      <view class="menu-row" v-for="(row, rowIdx) in menuList" :key="rowIdx">
        <navigator 
          class="menu-item" 
          v-for="(item, idx) in row" 
          :key="item.id"
          :url="item.url"
          open-type="navigate"
          @click="handleMenuClick(item)"
          :class="{ 'menu-item--single': row.length === 1 }"
        >
          <view class="menu-icon" :style="{ backgroundColor: item.color }">
            <text class="icon-placeholder">{{ item.iconText }}</text>
          </view>
          <text class="menu-text">{{ item.name }}</text>
        </navigator>
      </view>
    </view>

    <!-- 3. 操作按钮区（优化适配与反馈） -->
    <view class="action-area">
      <view class="btn-group" v-if="!isLogin">
        <navigator 
          class="btn login-btn" 
          url="/pages/login/login"
        >
          登录
        </navigator>
        <navigator 
          class="btn reg-btn" 
          url="/pages/login/reg"
        >
          注册
        </navigator>
      </view>

      <button 
        class="btn logout-btn" 
        v-if="isLogin"
        @click="handleLogout"
        hover-class="logout-btn--active"
      >
        退出登录
      </button>
    </view>

    <!-- 底部安全区域适配 -->
    <view class="safe-area-bottom"></view>
  </view>
</template>

<script>
import { myRequest } from '@/util/request.js';
export default {
  name: "Mine",
  data() {
    return {
      defaultAvatar: '/static/img/default-avatar.png',
      userInfo: {
        id: "",
        username: "",
        phone: "",
        avatar: ""
      },
      isLogin: false,
      menuList: [
        [
          { 
            id: 1,
            name: "我的书架", 
            url: "/pages/bookshelf/bookshelf", 
            color: "#3E88F0", 
            iconText: "📚"
          }
        ],
        [
          { 
            id: 2,
            name: "个人信息", 
            url: "/pages/profile/profile", 
            color: "#4CD964", 
            iconText: "👤"
          },
          { 
            id: 3,
            name: "帮助中心", 
            url: "/pages/help/help", 
            color: "#FF9500", 
            iconText: "❓"
          }
        ]
      ]
    };
  },
  onLoad() {
    this.initLoginStatus();
  },
  onShow() {
    this.initLoginStatus();
  },
  methods: {
    handleMenuClick(item) {
      if (!item.url || item.url.trim() === "") {
        uni.showToast({ title: "功能暂未开放", icon: "none" });
        return false;
      }
      
      // 未登录时拦截需权限的页面，引导登录
      if (!this.isLogin && !this.isAuthPage(item.url)) {
        uni.showModal({
          title: "提示",
          content: "请先登录使用该功能",
          confirmText: "去登录",
          cancelText: "取消",
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({ url: "/pages/login/login" });
            }
          }
        });
        return false;
      }
    },
    
    // 判断是否为不需要登录的页面
    isAuthPage(url) {
      const authPages = ['/pages/login/login', '/pages/login/reg'];
      return authPages.some(page => url === page);
    },
    
    async initLoginStatus() {
      const token = uni.getStorageSync('token');
      if (!token) {
        this.isLogin = false;
        this.userInfo = { id: '', username: '', phone: '', avatar: '' };
        return;
      }
      try {
        const data = await myRequest({ url: '/api/user/info', method: 'GET' });
        this.userInfo = data;
        this.isLogin = true;
        uni.setStorageSync('userInfo', data);
      } catch (e) {
        // token失效会被myRequest处理，这里回落为未登录态
        this.isLogin = false;
        this.userInfo = { id: '', username: '', phone: '', avatar: '' };
      }
    },
    
    handleLogout() {
      uni.showModal({
        title: "提示",
        content: "确定要退出登录吗？",
        confirmText: "退出",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            try {
              uni.removeStorageSync("userInfo");
              uni.removeStorageSync("token");
              this.initLoginStatus();
              uni.showToast({ 
                title: "退出成功", 
                icon: "success",
                duration: 1500
              });
              
              // 退出后返回首页，兼容不同路由结构
              setTimeout(() => {
                // 尝试切换到tabBar首页
                uni.switchTab({
                  url: "/pages/index/index",
                  fail: () => {
                    // 如果失败，使用navigateTo
                    uni.navigateTo({
                      url: "/pages/index/index",
                      fail: () => {
                        // 如果仍失败，使用reLaunch
                        uni.reLaunch({ url: "/pages/index/index" });
                      }
                    });
                  }
                });
              }, 1500);
            } catch (err) {
              console.error("退出登录失败:", err);
              uni.showToast({ title: "退出失败，请重试", icon: "none" });
            }
          }
        }
      });
    },
    
    // 图片加载失败容错
    handleImgError(e) {
      // 避免无限循环
      if (e.target.src !== this.defaultAvatar) {
        e.target.src = this.defaultAvatar;
      }
    }
  }
};
</script>

<style scoped lang="scss">
/* 基础变量优化 */
$primary-color: #3E88F0;
$secondary-color: #4CD964;
$help-color: #FF9500;
$gray-light: #F5F7FA;
$gray-mid: #999999;
$gray-dark: #333333;
$gap-size: 20rpx;
$btn-radius: 60rpx;
$border-width: 4rpx;
// 安全区域适配，增加兼容性
$safe-area: env(safe-area-inset-bottom, 0px);
$safe-area-fallback: constant(safe-area-inset-bottom, 0px);

/* 页面基础样式 */
page {
  background-color: $gray-light;
  min-height: 100vh;
  box-sizing: border-box;
  padding-top: 0;
}

/* 根容器 */
.mine-page {
  display: flex;
  flex-direction: column;
  gap: $gap-size * 1.5;
  // 使用变量和fallback适配安全区域
  padding-bottom: calc(#{$safe-area} + 30rpx);
  flex: 1;
}

/* 1. 用户信息区 */
.user-info-container {
  background: linear-gradient(135deg, #3E88F0 0%, #4CD964 100%);
  border-radius: 0 0 30rpx 30rpx;
  padding: 40rpx $gap-size * 2 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: $gap-size * 2;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.avatar-wrap {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: $gap-size * 2;
  border: 4rpx solid #FFFFFF;
  box-shadow: 0 4rpx 12rpx rgba(62, 136, 240, 0.3);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-detail {
  flex: 1;
  min-width: 0;
}

.nickname {
  font-size: 36rpx;
  color: $gray-dark;
  font-weight: 600;
  margin-bottom: 8rpx;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-id {
  font-size: 22rpx;
  color: $primary-color;
  margin-bottom: 4rpx;
  display: block;
}

.desc {
  font-size: 22rpx;
  color: $gray-mid;
  line-height: 1.4;
}

.login-btn--small {
  padding: 12rpx 24rpx;
  background-color: $primary-color;
  color: #FFFFFF;
  border-radius: 40rpx;
  font-size: 24rpx;
  text-align: center;
  min-width: 120rpx;
}

/* 2. 功能菜单区 */
.menu-list {
  padding: 0 $gap-size * 2;
}

.menu-row {
  display: flex;
  justify-content: space-between;
  gap: $gap-size;
  margin-bottom: $gap-size;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: calc(50% - $gap-size / 2);
  padding: $gap-size * 2.5;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  transition: all 0.2s ease;
  
  &:hover, &:active {
    background-color: $gray-light;
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);
    transform: translateY(-2rpx);
  }
}

.menu-item--single {
  margin: 0 auto;
  width: auto;
  min-width: 200rpx;
}

.menu-icon {
  width: 72rpx;
  height: 72rpx;
  border-radius: 50%;
  margin-bottom: 18rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #FFFFFF;
  font-size: 36rpx;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

.menu-text {
  font-size: 28rpx;
  color: $gray-dark;
  text-align: center;
  line-height: 40rpx;
  font-weight: 500;
}

/* 3. 操作按钮区 */
.action-area {
  display: flex;
  justify-content: center;
  padding: $gap-size 0;
  margin-top: $gap-size;
}

.btn-group {
  display: flex;
  gap: $gap-size * 2;
  align-items: center;
  width: 100%;
  max-width: 500rpx;
  padding: 0 $gap-size * 2;
  box-sizing: border-box;
}

.btn {
  padding: 22rpx 0;
  border-radius: $btn-radius;
  font-size: 28rpx;
  text-align: center;
  flex: 1;
  box-sizing: border-box;
  transition: all 0.2s ease;
}

.login-btn {
  background-color: $primary-color;
  color: #FFFFFF;
  border: none;
  
  &:hover, &:active {
    background-color: #2A70E0;
  }
}

.reg-btn {
  background-color: #FFFFFF;
  color: $primary-color;
  border: $border-width solid $primary-color;
  
  &:hover, &:active {
    background-color: rgba(62, 136, 240, 0.05);
  }
}

.logout-btn {
  background-color: #FFFFFF;
  color: #FF4D4F;
  border: $border-width solid #FF4D4F;
  width: 300rpx;
  
  &:hover, &:active {
    background-color: rgba(255, 77, 79, 0.05);
  }
}

/* 底部安全区域占位 */
.safe-area-bottom {
  height: $safe-area;
}
</style>